package com.bwie.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.bwie.pojo.TbPassenger;
import com.bwie.utils.FileUploadUtil;
import com.bwie.utils.HttpUtils;
import com.bwie.utils.OcrIdCard;
import com.bwie.utils.R;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: TODO
 * @author LiuWei Chen
 * @date 2025/9/8 14:24
 * @version 1.0
 */

@RestController
@RequestMapping("/server/index")
public class IndexController {
    @PostMapping("ocrCard")
    public R ocrCard(@RequestPart("imgFile") MultipartFile imgFile){
        TbPassenger passenger = new TbPassenger();
        String tempFilePath = null;
        JSONObject res_obj = new JSONObject();
        try {
            tempFilePath = FileUploadUtil.convertMultipartFileToPath(imgFile);
            String host = "https://cardnumber.market.alicloudapi.com";
            String path = "/rest/160601/ocr/ocr_idcard.json";
            String appcode = "f05d3ed0d0794c74a743aab6ce0f10eb"; // 注意保护你的appcode
            String method = "POST";

            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + appcode);
            headers.put("Content-Type", "application/json; charset=UTF-8");

            Map<String, String> querys = new HashMap<String, String>();
            // 对图像进行base64编码
            String imgBase64 = OcrIdCard.img_base64(tempFilePath);
            // 配置
            JSONObject configObj = new JSONObject();
            configObj.put("side", "face"); // 正面
            String config_str = configObj.toString();
            // 拼装请求体
            JSONObject requestObj = new JSONObject();
            requestObj.put("image", imgBase64);
            if(configObj.size() > 0) {
                requestObj.put("configure", config_str);
            }
            String bodys = requestObj.toString();
            try {
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if(stat != 200){
                    System.out.println("Http code: " + stat);
                    System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                    System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                    return R.ERROR(500, "请上传正确的身份证图片！");
                }
                String res = EntityUtils.toString(response.getEntity());
                res_obj = JSON.parseObject(res);
                System.out.println("OCR识别结果: " + res_obj.toJSONString()); // 打印完整结果以便调试

                // 检查是否有错误信息
                if (res_obj.containsKey("error_code")) {
                    String errorMsg = res_obj.getString("error_msg");
                    return R.ERROR(500, "识别失败: " + errorMsg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.ERROR(500, "识别过程出错");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 确保临时文件被删除
            if (tempFilePath != null) {
                FileUploadUtil.deleteTempFile(tempFilePath);
            }
        }
        try {
            String address = res_obj.getString("address");
            String num = res_obj.getString("num"); // 或"idcard_number"，取决于接口返回
            String sex = res_obj.getString("sex");
            String name = res_obj.getString("name");
            // 赋值给实体类
            passenger.setPassengerName(name);
            passenger.setPassengerCard(num);
            passenger.setPassengerSex(sex);
            passenger.setPassengerAddress(address);
            return R.OK(passenger);
        } catch (JSONException e) {
            // 捕获JSON解析异常，便于调试
            e.printStackTrace();
            return R.ERROR(500, "解析识别结果失败: " + e.getMessage() + "，请检查字段名是否正确");
        }
    }
}
